// src/stores/productCategory.js
import { defineStore } from 'pinia'
import {
  listAllProductCategoriesAPI,
  addProductCategoryAPI,
  updateProductCategoryAPI,
  deleteProductCategoryAPI,
  getProductCategoryAPI,
  toggleCategoryStatusAPI,
  searchProductCategoryByNameAPI
} from '@/api/productCategoryAPI'

export const useProductCategoryStore = defineStore('productCategory', {
  state: () => ({
    categories: [],
    total: 0,
    currentPage: 1,
    pageSize: 10,
    loading: false,
    selectedCategory: null
  }),

  actions: {
    // 获取所有商品类目
    async fetchCategories() {
      this.loading = true
      try {
        const res = await listAllProductCategoriesAPI()
        
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          // 后端返回的是 List<ProductCategoryInfoDTO>
          if (Array.isArray(res.data)) {
            this.categories = res.data
            this.total = res.data.length
          } else {
            this.categories = []
            this.total = 0
          }
        } else {
          console.error('获取商品类目列表失败:', res?.message || '未知错误')
          this.categories = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取商品类目失败:', error)
        this.categories = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 根据类目名称搜索类目
    async searchCategoriesByName(name) {
      this.loading = true
      try {
        const res = await searchProductCategoryByNameAPI(name)

        if (res && (res.code === 0 || res.code === 200) && res.data) {
          if (Array.isArray(res.data)) {
            this.categories = res.data
            this.total = res.data.length
          } else {
            this.categories = []
            this.total = 0
          }
        } else {
          console.error('搜索商品类目失败:', res?.message || '未知错误')
          this.categories = []
          this.total = 0
        }
      } catch (error) {
        console.error('搜索商品类目失败:', error)
        this.categories = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 新增商品类目
    async addCategory(categoryData) {
      try {
        const res = await addProductCategoryAPI(categoryData)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchCategories()
          return { success: true }
        } else {
          throw new Error(res?.message || '添加商品类目失败')
        }
      } catch (error) {
        console.error('新增商品类目失败:', error)
        throw error
      }
    },

    // 编辑商品类目
    async updateCategory(id, categoryData) {
      try {
        const res = await updateProductCategoryAPI(id, categoryData)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchCategories()
          return { success: true }
        } else {
          throw new Error(res?.message || '更新商品类目失败')
        }
      } catch (error) {
        console.error('更新商品类目失败:', error)
        throw error
      }
    },

    // 删除商品类目
    async deleteCategory(id) {
      try {
        const res = await deleteProductCategoryAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchCategories()
          return { success: true }
        } else {
          throw new Error(res?.message || '删除商品类目失败')
        }
      } catch (error) {
        console.error('删除商品类目失败:', error)
        throw error
      }
    },

    // 获取单个商品类目详情
    async getCategoryById(id) {
      try {
        const res = await getProductCategoryAPI(id)
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          this.selectedCategory = res.data
          return res.data
        } else {
          throw new Error(res?.message || '获取商品类目详情失败')
        }
      } catch (error) {
        console.error('获取商品类目详情失败:', error)
        throw error
      }
    },

    // 切换类目状态
    async toggleCategoryStatus(id) {
      try {
        const res = await toggleCategoryStatusAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchCategories()
          return { success: true }
        } else {
          throw new Error(res?.message || '切换类目状态失败')
        }
      } catch (error) {
        console.error('切换类目状态失败:', error)
        throw error
      }
    }
  }
})